
'use strict';

const Controller = require('egg').Controller;
const crypto = require('crypto');
const svgCaptcha = require('svg-captcha');
class RegController extends Controller {
  
  //用户登录前端界面
  async loginShow() {
    const {ctx} = this;
    await ctx.render('login.ejs', {
        title: '用户登录',
        user: ctx.session.user,
        success: "",
        error: ""
    })
  }

  // 用户注册前端界面
  async registerShow() {
    const {ctx} = this;
    await ctx.render('reg.ejs', {
        title: '用户注册',
        user: ctx.session.user,
        success: "",
        error: ""
    })
  }

  //登录
  async login(){

    const ctx = this.ctx;

    let body = ctx.request.body

    let md5 = crypto.createHash('md5');

    let password = md5.update(body.password).digest('hex');

    const users = await this.service.users.findOne({name:body.name});

    //如果没有重名的，则存储
    if(users.name){
      if (users.password != password) {
          console.log("密码错误")
          return ctx.redirect('/login');
      }
      ctx.session.user = users;
      return ctx.redirect('/');
    }else{
      console.log("用户不存在")
      return ctx.redirect('/login')
    }
  }

  //退出登录
  async logOut(){
    const ctx = this.ctx;
    ctx.session.user = null;
    ctx.redirect('/');
  }

  // 注册
  async register(){

    const ctx = this.ctx;

    let body = ctx.request.body

    const createRule = {
      name: 'string',
      password: 'string',
      repassword: 'string',
      email: 'string',
      captcha:'number',
      sRole:'string'
    };

    if(body.name == "" || body.password == ""){
      console.log("用户名和密码不能为空")
      // ctx.body="用户名和密码不能为空"
      return ctx.redirect('/reg')
    }   

    //检验用户两次输入的密码是否一致
    if (body.repassword != body.password) {
        console.log('两次输入的密码不一致')
        return ctx.redirect('/reg');
    }

    if(body.captcha == "" || body.captcha != ctx.session.register_code){
      console.log("验证码不能为空或填写错误");
      return ctx.redirect('/reg')
    } 

    body.password = crypto.createHash('md5').update(body.password).digest('hex')
    delete body.repassword

    // 如果参数校验未通过，将会抛出一个 status = 422 的异常
    // ctx.validate(createRule, body);
    const users = await this.service.users.findAll({name:body.name});

    //如果没有重名的，则存储
    if(!users.length){
      let users = await this.service.users.add(body);
      console.log("success register")
      ctx.session.user = users;
      return ctx.redirect('/');
    }else{
      console.log("已经存在");
      return ctx.redirect('/reg');
    }
  }

  //生成注册验证码
  async getCaptcha(){

    const ctx = this.ctx;

    var captcha = svgCaptcha.createMathExpr({
      noise:3,
      // color:true
    });

    ctx.session.register_code = captcha.text;

    ctx.body = captcha.data
  }

}
module.exports = RegController;
